package proxyServer;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

public class MyProgram
{
	
	final static int defaultServerPort = 5555;
	final static int maxServerPort     = 65536;
	
	/**
	 * @param args
	 */
	public static void main(String[] args)
	{
		// ProxyXML prxml = new ProxyXML();
		// prxml.readXML();
		
		// prxml.writeXML();
		
		// prxml.modifyXML();
		
		int serverPort = 0;
		switch (args.length)
		{
			case 0:
				serverPort = defaultServerPort;
				break;
			case 1:
				try
				{
					serverPort = Integer.parseInt(args[0]);
				}
				catch (NumberFormatException e)
				{
					// TODO: handle exception
					System.err.println("Error: Invalid server port.");
					return;
				}
				if (serverPort > maxServerPort)
				{
					System.err.println("Error: Invalid server port.");
					return;
				}
				break;
			default:
				System.out.println("Usage: Server [port].");
				return;
		}
		ServerSocket serverSocket = null;
		
		try
		{
			serverSocket = new ServerSocket(serverPort);
			while (true)
			{
				// System.out.println("Starting the MyproxyServer ...");
				Socket socket = serverSocket.accept();
				ProxyThread pt = new ProxyThread(socket);
				pt.start();
			}
			
		}
		catch (IOException e)
		{
			// TODO: handle exception
			System.err.println("Proxy shutting down");
		}
		catch (Exception e)
		{
			// TODO: handle exception
		}
		finally
		{
			try
			{
				serverSocket.close();
				
			}
			catch (Exception ex)
			{
				// TODO: handle exception
				System.exit(0);
			}
			
		}
	}
	
}
